package com.zhang.table;

import com.zhang.second.utils.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @title:
 * @author: zhang
 * @date: 2022/2/10 15:49
 */
public class StreamToTable {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<SensorReading> sensorReadingDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, SensorReading>() {
                    @Override
                    public SensorReading map(String value) throws Exception {
                        String[] fields = value.split(" ");
                        return new SensorReading(
                                fields[0], Integer.parseInt(fields[1])
                        );
                    }
                });

        //获取流表环境
        StreamTableEnvironment streamTableEnvironment = StreamTableEnvironment.create(env);

        //将流转换为动态表
        Table table = streamTableEnvironment.fromDataStream(sensorReadingDS);

        //使用table api
        Table result = table.where($("sensorId").isEqual("ws_001"))
                .select($("sensorId"), $("temperature"));

        //将表转化为流打印
        DataStream<Row> rowDataStream = streamTableEnvironment.toAppendStream(result, Row.class);
        rowDataStream.print();

        env.execute();
    }
}
